package m202311.d06;

/**
 * @author haocongshun
 * @date 2023/11/06 18:40:24
 */

/**
 * 122. 买卖股票的最佳时机 II
 */
public class Q122 {

    public static void main(String[] args) {
        int i = new Q122().maxProfit(new int[]{2, 1, 2, 0, 1});
        System.out.println(i);
    }

    public int maxProfit(int[] prices) {
        int res = 0;
        int min = prices[0];
        int temp = 0;
        for (int i = 1; i < prices.length; i++) {
            int diff = prices[i] - min;
            if (diff < 0) {
                min = prices[i];
                res = res + temp;
                temp = 0;
            } else if (diff < temp) {
                res = res + temp;
                min = prices[i];
                temp = 0;
            } else {
                temp = diff;
            }
        }
        return res + temp;
    }
}
